//
//  WebViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/30.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import WebKit
import JavaScriptCore

enum H5page: String {
    case registere = "app/getconfig/register"                           //注册协议
    case privacy = "app/getconfig/privacy"                              //隐私协议
    case refuel = "app/getconfig/refuel"                                //加油规则
    case overtime = "app/getconfig/overtime"                            //加时规则
    case legend = "images/legend.jpg"                                   //图例
    case regular = "app/getconfig/regular"                              //时租计费规则
    case dateRule = "app/getconfig/day_regular"                         //日租计费规则
    case otherCityreturncar = "app/getconfig/return_car_instruction"    //异地还车说明
    case boundBankCard = "app/getconfig/bind_card_agreement"            //支付协议
    case redpack = "app/getconfig/redpack_car"                          //红包车规则说明
    case unCountDamage = "app/getconfig/no_deduct_agreement"            //不计免赔
    case preorderRule = "app/getconfig/preorder_rule"                   //预约用车规则说明
}

enum Page {
    case server(H5page)
    case other(Ad.Image)
    case URL(String)
}

class WebViewController: UIViewController {
    
    var page: Page!
    
    var webView: WKWebView!
    
    var payment: Order.Pay.Payment?
    let config = WKWebViewConfiguration()
    
    @IBOutlet weak var shareButton: UIButton!
        
    override func viewDidLoad() {
        super.viewDidLoad()
        //监听分享状态
        addObserve()
        config.preferences = WKPreferences()
        config.preferences.javaScriptEnabled = true
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        config.userContentController = WKUserContentController()
        config.processPool = WKProcessPool()
        
        config.userContentController.add(self, name: "pay")
        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.navigationDelegate = self

        view.addSubview(webView)

        webView.snp.makeConstraints { make in
            make.top.equalTo(44)
            make.bottom.left.right.equalTo(0)
        }
        if let page = page {
            switch page {
            case let .server(p):
                if let url = URL(string: kServerName + "../" + p.rawValue) {

                    navigationItem.rightBarButtonItem = nil
                    webView.load(URLRequest(url: url))
                }
            case let .other(ad):
                if ad.shareFlag == 1 {
                    navigationItem.rightBarButtonItem = nil
                }

                if let url = URL(string: ad.adURL) {
                    webView.load(URLRequest(url: url))
                    self.title = ad.adName
                }
            case let .URL(url):
                if let url = URL(string: url) {
                    navigationItem.rightBarButtonItem = nil
                    webView.load(URLRequest(url: url))
                }
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        config.userContentController.removeScriptMessageHandler(forName: "pay")

    }
    
    func addObserve () {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.payblock { [weak self] response in
                if let payment = self?.payment {
                    switch payment {
                    case .aliPay:
                        if let value = response as? [AnyHashable : AnyObject] {
                            let code = value["resultStatus"] as? String
                            if code == "9000" {
                                XHProgressHUD.showSuccess("支付成功")
                                self?.dismiss(animated: true, completion: nil)
                            } else {
                                XHProgressHUD.showError("取消了支付")
                            }
                        }
                    case .wePay:
                        if let model = response as? BaseResp {
                            if model.errCode == -2 {
                                XHProgressHUD.showError("取消了支付")
                            } else {
                                XHProgressHUD.showSuccess("支付成功")
                                self?.dismiss(animated: true, completion: nil)
                            }
                        }
                    case .balance, .ticket:break
                    }
                } else {
                    //  分享
                    
                    let model = response as! BaseResp
                    print("ooooo:",model.errCode) 
                    if model.errCode == -2 {
                        XHProgressHUD.showError("取消了分享")
                    } else {
                        XHProgressHUD.showSuccess("分享成功")
                    }
                }
            }
            
        }
    }
    
    @IBAction func sharePage(_ sender: Any) {
        
        if !User.isLogin() {
            let vc = userInfoStory.instantiateViewController(withIdentifier: "LoginViewController")
            present(vc, animated: true, completion: nil)
        } else {
            let actionSheet = UIAlertController(title: "请选择分享平台", message: nil, preferredStyle: .actionSheet)
            actionSheet.addAction(UIAlertAction(title: "朋友圈", style: .default, handler: { [weak self] action in
                self?.share(1)
            }))
            actionSheet.addAction(UIAlertAction(title: "微信", style: .default, handler: { [weak self] action in
                self?.share(2)
            }))
            
            actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            
            present(actionSheet, animated: true, completion: nil)
        }
    }
    
    func share(_ platform: Int) {
        guard let user = User.info() else {
            return
        }
        //点击分享的时候支付方式重置
        self.payment = nil
        
        let message = WXMediaMessage()
        let webpageOject = WXWebpageObject()
        
        if let page = page {
            switch page {
            case let .other(ad):
                message.title = ad.shareTitle
                message.description = ad.shareContent
                message.setThumbImage(UIImage(named: "logo002"))

                if ad.shareUrl.contains("?") {
                    webpageOject.webpageUrl = "\(ad.shareUrl)&invite_user_id=\(user.userId)"
                } else {
                    webpageOject.webpageUrl = "\(ad.shareUrl)?invite_user_id=\(user.userId)"
                }
                
            case let .server(u):
                p(u)
            case let .URL(url):
                p(url)
            }
        }
        message.mediaObject = webpageOject
        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = platform == 1 ? Int32(WXSceneTimeline.rawValue) : Int32(WXSceneSession.rawValue)
        WXApi.send(req)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func close(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
}

extension WebViewController: WKNavigationDelegate {
    
}

extension WebViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
        
        if let b = message.body as? [Any],
            let p = b[0] as? Int,
            let s = b[1] as? String ,
            let payment = Order.Pay.Payment(rawValue: p) {
            self.payment = payment
            switch payment {
            case .aliPay:
                Pay.zhifuPay(payStr: s)
            case .wePay:
                Pay.wechatPay(payStr: s)
            case .balance, .ticket:
                break
            }
        }
    }
}
